﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ones.ServiceNewsManagement;
using Ones.ServiceHumanResourceManagement;
using System.Transactions;

namespace Ones.Editorial.Editor
{
    public partial class ENewsEdit : System.Web.UI.Page
    {
        #region Events
        private ServiceNewsManagement.ServiceNewsManagementClient srvNewsMngmt = null;
        private ServiceCategoryManagement.ServiceCategoryManagementClient srvCatMngmt = null;
        private ServiceHumanResourceManagement.ServiceHumanResourceManagementClient srvHrMngmt = null;
        string userAccount = string.Empty;
        int newsID = 0;

        enum processStatus
        {
            Approved,
            Edited,
            Posted,
            RejectedA,
            RejectedE
        }

        enum processDirection
        {
            Post,
            Reject
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            successfulMsg.Visible = false;
            failMsg.Visible = false;

            if (Session["user"] != null)
            {
                userAccount = Session["user"].ToString();
            }
            else { userAccount = "emp000008"; }

            if (!Page.IsPostBack)
            {
                this.BindDisplayedNews();
            }

        }

        protected void NewsUpdate_Confirm(object sender, CommandEventArgs e)
        {
            string alertNewsUpdateFailed = "alert('News cannot be updated due to invalid process status or incorrect owner!');";
            switch (e.CommandName.ToString())
            {
                case "cmdSave":
                    if (this.ValidateNewsUpdate("Edit"))
                    {
                        if (this.EditNews())
                        {
                            successfulMsg.Visible = true;
                            failMsg.Visible = false;
                        }
                        else
                        {
                            successfulMsg.Visible = false;
                            failMsg.Visible = true;
                        }
                    }
                    else
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", alertNewsUpdateFailed, true);
                        //Display message that news cannot be updated due to invalid process status or user's role
                    }
                    break;
                case "cmdReject":
                    if (this.ValidateNewsUpdate("Reject"))
                    {
                        if (this.RejectNews())
                        {
                            successfulMsg.Visible = true;
                            failMsg.Visible = false;
                        }
                        else
                        {
                            successfulMsg.Visible = false;
                            failMsg.Visible = true;
                        }
                    }
                    else
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", alertNewsUpdateFailed, true);
                    }
                    break;
                case "cmdCancel":
                    //Back to NewsDisplay.aspx
                    Response.Redirect("~/Editorial/Writer/NewsDisplay.aspx");
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region Methods
        private void BindDisplayedNews()
        {
            newsID = Convert.ToInt32(Session["newsId"]);

            srvNewsMngmt = new ServiceNewsManagement.ServiceNewsManagementClient("newsWsHttpBinding");
            srvCatMngmt = new ServiceCategoryManagement.ServiceCategoryManagementClient("catWsHttpBinding");

            Ones.ServiceNewsManagement.News n = new Ones.ServiceNewsManagement.News();

            n = srvNewsMngmt.RetrieveNewsByID(newsID);
            txtTitle.Value = n.newsTitle;

            ddlCategory.DataSource = srvCatMngmt.searchAllCategories();
            ddlCategory.DataBind();
            ddlCategory.SelectedValue = n.catId;

            txtNewsIntro.Value = n.newsIntroduceText;
            lblAuthor.InnerText = n.author;
            telerikNewsEditor.Text = n.newsContent;
            lblEditor.InnerText = userAccount;
        }

        private bool ValidateNewsUpdate(string action)
        {
            srvNewsMngmt = new ServiceNewsManagementClient("newsWsHttpBinding");
            srvHrMngmt = new ServiceHumanResourceManagementClient("hrBasicHttpBinding");

            var n = srvNewsMngmt.RetrieveNewsByID(Convert.ToInt32(Session["newsId"]));

            IList<JobAssignment> jaSearhEditor = srvHrMngmt.searchDivisionByEmpId(userAccount);
            var jaEditor = jaSearhEditor.First<JobAssignment>();

            IList<JobAssignment> jaSearchAuthor = srvHrMngmt.searchDivisionByEmpId(n.author);
            var jaAuthor = jaSearchAuthor.First<JobAssignment>();

            if (action.Equals("Edit"))
            {
                if ((n.processStatus.Equals("RejectedA") || n.processStatus.Equals("Posted")) && jaEditor.divId == jaAuthor.divId)
                    return true;
                return false;
            }
            else if (action.Equals("Reject"))
            {
                if (n.processStatus.Equals("Posted") && jaEditor.divId == jaAuthor.divId)
                    return true;
                return false;
            }
            else
            {
                return false;
            }
        }

        private bool EditNews()
        {
            DateTime currentDate = System.DateTime.Now;

            using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    srvNewsMngmt = new ServiceNewsManagementClient("newsWsHttpBinding");

                    Ones.ServiceNewsManagement.News n = new Ones.ServiceNewsManagement.News();
                    Ones.ServiceNewsManagement.NewsVersion nv = new Ones.ServiceNewsManagement.NewsVersion();

                    var currentNews = srvNewsMngmt.RetrieveNewsByID(Convert.ToInt32(Session["newsId"]));

                    currentNews.newsTitle = txtTitle.Value;
                    currentNews.catId = ddlCategory.SelectedValue;

                    currentNews.newsIntroduceText = txtNewsIntro.Value;
                    currentNews.newsContent = telerikNewsEditor.Text;
                    currentNews.modificationDate = currentDate;
                    currentNews.processStatus = processStatus.Edited.ToString();

                    nv.verSender = userAccount;
                    nv.verEditor = userAccount;
                    nv.verProcessDirection = processDirection.Post.ToString();
                    nv.verComments = txtComment.Value;
                    nv.verDate = currentDate;

                    bool result = srvNewsMngmt.UpdateNews(currentNews, nv);
                    if (result)
                    {
                        trans.Complete();
                        return true;
                        //Response.Redirect("~/Editorial/Writer/NewsDisplay.aspx");
                    }
                    return false;
                }
                catch (TransactionException ex)
                {
                    trans.Dispose();
                    return false;
                }
            }
        }

        private bool RejectNews()
        {
            DateTime currentDate = System.DateTime.Now;

            using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    srvNewsMngmt = new ServiceNewsManagementClient("newsWsHttpBinding");

                    Ones.ServiceNewsManagement.News n = new Ones.ServiceNewsManagement.News();
                    Ones.ServiceNewsManagement.NewsVersion nv = new Ones.ServiceNewsManagement.NewsVersion();

                    var currentNews = srvNewsMngmt.RetrieveNewsByID(Convert.ToInt32(Session["newsId"]));

                    currentNews.processStatus = processStatus.RejectedE.ToString();

                    nv.verSender = userAccount;
                    nv.verEditor = userAccount;
                    nv.verProcessDirection = processDirection.Reject.ToString();
                    nv.verComments = txtComment.Value;
                    nv.verDate = currentDate;

                    bool result = srvNewsMngmt.ReviseNews("RejectE", currentNews, nv);
                    if (result)
                    {
                        trans.Complete();
                        return true;
                        //Response.Redirect("~/Editorial/Writer/NewsDisplay.aspx");
                    }
                    return false;
                }
                catch (TransactionException ex)
                {
                    trans.Dispose();
                    return false;
                }
            }
        }

        #endregion
    }
}